<template>
	<div class="cost-wrap">
		<div class="module-box pb30">
			<div class="flex-between el-form-sub-title font-bold">
				年份酒价值概况
				<span class="time">数据截止{{ dayjs().format('YYYY-MM-DD HH:mm:ss') }}</span>
			</div>
			<div class="flex mt20">
				<div class="mr30">
					<div class="sub-title">
						在库总数量<el-tooltip class="box-item" effect="light" content="筛选时间内，年份酒在库总库存数量" placement="top">
							<el-icon color="#888" class="mt-3 ml5" style="vertical-align: middle">
								<QuestionFilled />
							</el-icon>
						</el-tooltip>
					</div>
					<div class="font20 mt10 mb5">{{ baseData?.total }}</div>
				</div>
				<div class="mr20">
					<div class="sub-title">
						在库总价值<el-tooltip class="box-item" effect="light" content="筛选时间内，年份酒在库总库存价值" placement="top">
							<el-icon color="#888" class="mt-3 ml5" style="vertical-align: middle">
								<QuestionFilled />
							</el-icon>
						</el-tooltip>
					</div>
					<div class="font20 mt10 mb5">{{ fenToYuan(baseData?.totalValue) }}</div>
				</div>
			</div>
			<div class="grid mt20">
				<div class="grid-content ep-bg-purple" v-for="item in baseData?.list" :key="item.name">
					<div class="sub-title">{{ item.name }}</div>
					<div class="mt10">
						<span class="mr15">库存：{{ item.totalInventory }} </span>价值：{{ fenToYuan(item.totalValue) }}
					</div>
				</div>
			</div>
		</div>
		<div class="module-box pb30 mt20">
			<div class="el-form-sub-title font-bold">年份酒价值趋势</div>
			<div class="mb20 flex-between">
				<div>
					<span class="mr10">时间筛选</span>
					<el-date-picker
						v-model="dateRangeValue"
						type="daterange"
						unlink-panels
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:shortcuts="shortcuts"
						:disabled-date="disabledDate"
						@change="handleDateChange"
					/>
				</div>
				<el-button type="primary" plain @click="onValueExport" v-auth="'data:value:trend:analysis:export'">导出数据</el-button>
			</div>
			<el-radio-group v-model="radioValue" class="w-full mb20">
				<el-radio v-for="item in chartDatas.options" :key="item" :value="item"> {{ item }} </el-radio>
			</el-radio-group>
			<div class="chart-wrap">
				<LineCharts :option="{ data: chartDatas[radioValue] || [], xData: chartDatas.xData, legend: chartDatas.legend, legendHide: true }" />
			</div>
		</div>
		<div class="module-box pb30 mt20">
			<div class="el-form-sub-title font-bold">年份酒价值明细</div>
			<div class="mb20 flex-between">
				<div>
					<span class="mr10">时间筛选</span>
					<el-date-picker
						v-model="listDateValue"
						type="date"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:disabled-date="disabledDate"
						@change="handleListDateChange"
					/>
				</div>
				<el-button type="primary" plain @click="onExport" v-auth="'data:value:details:analysis:export'">导出数据</el-button>
			</div>
			<ProTable
				:searchCol="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }"
				ref="proTable"
				:columns="columns"
				:request-api="getTableList"
				:init-param="initParam"
			>
				<template #expand="scope">
					{{ scope.row }}
				</template>
			</ProTable>
		</div>
	</div>
</template>

<script setup lang="tsx" name="dataCost">
import { onMounted, ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import dayjs from 'dayjs';
import { NextLoading } from '/@/utils/loading';
import { fetchNfjValue, fetchNfjValueCharts, fetchNfjValueChartsExport, fetchNfjValueList, fetchNfjValueListExport } from '/@/api/data';
import { useDownload } from '/@/hooks/useDownload';
import LineCharts from '/@/components/chart/lineCharts.vue';
import { fenToYuan } from '/@/utils/commonFunction';
import ProTable from '/@/components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '/@/components/ProTable/interface';

const router = useRouter();
const route = useRoute();

const baseData = ref<any>({});

const dateRangeValue = ref([dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')]);
const listDateValue = ref(dayjs().subtract(1, 'day').format('YYYY-MM-DD'));

const radioValue = ref('0');
const chartDatas = ref<any>({
	options: [],
	xData: [],
});
const legend = [
	{ name: '在库总价值', code: 'nfjValue', type: 'price' },
	{ name: '在库总数量', code: 'nfjNums' },
];

const shortcuts = [
	{
		text: '昨天',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24);
			end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
			return [start, end];
		},
	},
	{
		text: '近7天',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
			return [start, end];
		},
	},
	{
		text: '近30天',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
			return [start, end];
		},
	},
];

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'materialCode',
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	params.startTime = dayjs(listDateValue.value).format('YYYY-MM-DD');
	return fetchNfjValueList(params);
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'matCode',
		label: '物料编码',
		minWidth: 100,
	},
	{
		prop: 'matName',
		label: '物料名称',
		minWidth: 200,
	},
	{
		prop: 'prodSaleLClassName',
		label: '产品大类',
		minWidth: 100,
	},
	{
		prop: 'productionYear',
		label: '生产年份',
		minWidth: 100,
	},
	{
		prop: 'pingchu',
		label: '瓶储年份',
		minWidth: 100,
	},
	{
		prop: 'nfjNums',
		label: '在库总数量',
		minWidth: 120,
	},
	{
		prop: 'nfjValue',
		label: '在库总价值',
		minWidth: 120,
		render: (scope) => {
			return fenToYuan(scope.row.nfjValue);
		},
	},
];

const handleDateChange = (val: any) => {
	getChartdata();
};

const disabledDate = (time: Date) => {
	return time.getTime() > Date.now();
};

const handleListDateChange = (val: any) => {
	proTable.value?.getTableList();
};

const getBaseData = async () => {
	const res: any = await fetchNfjValue({});
	baseData.value = res.data;
};

const getChartdata = async () => {
	const params = handleParams(dateRangeValue.value);
	const res: any = await fetchNfjValueCharts(params);
	const options = Object.keys(res.data);
	const data: any = {
		options,
		legend,
		xData: [],
	};
	options.forEach((item: any, ind: number) => {
		legend.map((i: any, index: number) => {
			const arr: any = [];
			res.data[item].forEach((item: any) => {
				if (index == 0 && ind == 0) {
					data.xData.push(item.report);
				}
				arr.push(i.type === 'price' ? fenToYuan(item[i.code]) : item[i.code]);
			});
			if (!data[item]) {
				data[item] = [];
			}
			data[item].push(arr);
		});
	});

	radioValue.value = options[0];
	chartDatas.value = data;
};

const handleParams = (dates: any[]) => {
	return {
		startTime: dayjs(dates[0]).format('YYYY-MM-DD'),
		endTime: dayjs(dates[1]).format('YYYY-MM-DD'),
	};
};

// 年份酒价值趋势导出
const onValueExport = () => {
	ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() =>
		useDownload(fetchNfjValueChartsExport, '年份酒价值趋势', handleParams(dateRangeValue.value))
	);
};

// 保存并导出
const onExport = () => {
	ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() =>
		useDownload(fetchNfjValueListExport, '年份酒价值明细', { startTime: listDateValue.value })
	);
};

// 页面加载时
onMounted(() => {
	getBaseData();
	getChartdata();
	NextLoading.done();
});
</script>

<style lang="scss">
.cost-wrap {
	.module-box {
		background: var(--el-color-white);
		padding: 20px;
		border-radius: var(--el-border-radius-round);
		box-sizing: border-box;
		.time {
			background: #f2f5f8;
			height: 32px;
			line-height: 32px;
			border-radius: 18px;
			font-size: 14px;
			font-weight: 400;
			padding: 0 16px;
			color: rgba($color: #000000, $alpha: 0.7);
			flex-shrink: 0;
		}
		.table-main {
			padding: 0;
		}
	}
	.sub-title {
		color: #666;
	}
	.grid {
		display: flex;
	}
	.grid-content {
		width: 20%;
	}
	.chart-wrap {
		height: 300px;
		width: 100%;
	}
}
</style>
